/*
 * PhoneGap is available under *either* the terms of the modified BSD license *or* the
 * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
 *
 * Copyright (c) 2005-2010, Nitobi Software Inc.
 * Copyright (c) 2010, IBM Corporation
 */
package com.phonegap.plugins.openIDAuth;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.util.Log;

import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;

public class OpenIDAuth extends Plugin {

	private String callback;


    /**
     * Executes the request and returns PluginResult.
     *
     * @param action        The action to execute.
     * @param args          JSONArry of arguments for the plugin.
     * @param callbackId    The callback id used when calling back into JavaScript.
     * @return              A PluginResult object with a status and message.
     */
    public PluginResult execute(String action, JSONArray args, String callbackId) {
        PluginResult.Status status = PluginResult.Status.NO_RESULT;
        String result = "";

        this.callback = callbackId;
        
        try {
            if (action.equals("showWebPage")) {
                result = this.showWebPage(args.getString(0));
                if (result.length() > 0) {
                    status = PluginResult.Status.ERROR;
                }
            }
            PluginResult pluginResult = new PluginResult(status, result);
            pluginResult.setKeepCallback(true);
            return pluginResult;
        } catch (JSONException e) {
            return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
        }
    }

    /**
     * Identifies if action to be executed returns a value and should be run synchronously.
     *
     * @param action    The action to execute
     * @return          T=returns value
     */
    public boolean isSynch(String action) {
        return false;
    }

    /**
     * Called by AccelBroker when listener is to be shut down.
     * Stop listener.
     */
    public void onDestroy() {
    }

    //--------------------------------------------------------------------------
    // LOCAL METHODS
    //--------------------------------------------------------------------------

    /**
     * Display a new browser with the specified URL.
     * 
     * NOTE: If usePhoneGap is set, only trusted PhoneGap URLs should be loaded,
     *       since any PhoneGap API can be called by the loaded HTML page.
     *
     * @param url           The url to load.
     * @return              "" if ok, or error message.
     */
    public String showWebPage(final String url) {
        try {
        	final OpenIDAuth oida = this;
        	Runnable runnable = new Runnable() {
        		public void run() {
        			new MyWebView(oida.ctx, url, new MyDialogListener(oida)).show();
        		};
        	};
        	this.ctx.runOnUiThread(runnable);
            return "";
        } catch (android.content.ActivityNotFoundException e) {
            System.out.println("OpenIDAuth: Error loading url " + url + ": " + e.toString());
            return e.toString();
        }
    }    

	/**
	* Callback interface for dialog requests.
	*
	*/
	public static interface DialogListener {
	
		        /**
		* Called when a dialog completes.
		*
		* Executed by the thread that initiated the dialog.
		*
		* @param values
		* Key-value string pairs extracted from the response.
		*/
		public void onComplete(Bundle values);
				
		/**
		* Called when a dialog has an error.
		*
		* Executed by the thread that initiated the dialog.
		*
		*/
		public void onError(DialogError e);
		
		/**
		* Called when a dialog is canceled by the user.
		*
		* Executed by the thread that initiated the dialog.
		*
		*/
		public void onCancel();
	
	}
	
	class MyDialogListener implements DialogListener {
		final OpenIDAuth oida;

		public MyDialogListener(OpenIDAuth oida){
			super();
			this.oida = oida;
		}

		public void onComplete(Bundle values) {
			// Handle a successful dialog
			Log.d("PhoneGapLog", values.toString());
    		String email = values.getString("email");
    		String identity = values.getString("identity");
    		JSONObject identityObject = new JSONObject();
    		try {
    			identityObject.put("email", email);
    			identityObject.put("identity", identity);
    		} catch (JSONException e) {
    			e.printStackTrace();
    		}
			this.oida.success(new PluginResult(PluginResult.Status.OK, identityObject), this.oida.callback);
		}

		public void onError(DialogError e) {
			e.printStackTrace();
		}

		public void onCancel() {
		}
	}
}
